package com.world.rickcloudendpoint.demo.redis.consumer;

import com.world.rickcloudendpoint.common.constant.GlobalConstants;
import com.world.rickcloudendpoint.demo.MsgConsumer;
import com.world.rickcloudendpoint.demo.QueueConstantKey;
import com.world.rickcloudendpoint.demo.local.LocalQueueFactory;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.AbstractQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @description:
 * @author: jlsong
 * @date: 2022/05/27 08:02:42
 * @version: 1.0
 */
@Component
@Log4j2
public class FiveConsumer implements MsgConsumer {
    @Resource
    LocalQueueFactory queueFactory;
    private final String queueName = QueueConstantKey.CACHE_PREFIX.concat(":").concat(QueueConstantKey.BUSINESS_FIVE);


    @Override
    public void onMessage(Object message) {
        try {
            // 解析消息并放入本地队列进行处理，缓存到内存中
            // 业务逻辑处理队列 名称

            AbstractQueue queue = queueFactory.getQueue(queueName);
            if (queue != null) {
                LinkedBlockingQueue blockingQueue = (LinkedBlockingQueue) queue;
                // 判断队列是否已满
                if (blockingQueue.remainingCapacity() < 0) {
                    log.info("queue[{}] is full,can not add item in queue.", queueName);
                    return;
                }
                blockingQueue.put(message);
            }
        } catch (Exception e) {
            log.error("put message into business[{}] queue failed,the reason is {} ",queueName,  e.getMessage(), e);
        }
    }

    @Override
    public void onError(Object message, Exception e) {
        log.error("消费者five=>存储消息发生错误", message, e);
    }

}
